package com.wars2donline.client.xml;

import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.badlogic.gdx.files.FileHandle;
import com.wars2donline.client.data.HeroData;

public class HeroDataXmlParser {
	
	class HeroDataHandler extends DefaultHandler {
		
		private HeroData mOutData = null;
		
		public HeroDataHandler(HeroData outData) {
			mOutData = outData;
		}
		
		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			
			
			System.out.println("startElement, uri : " + uri + "localName : " + localName + " qName : " + qName + " attribute length : " + attributes.getLength());
			
			if (qName.equals(XmlConstants.TAG_HERO)) {
				int id = Integer.parseInt(attributes.getValue(XmlConstants.TAG_HERO_ATTR_ID));
				int damage = Integer.parseInt(attributes.getValue(XmlConstants.TAG_HERO_ATTR_DAMAGE));
				int hp = Integer.parseInt(attributes.getValue(XmlConstants.TAG_HERO_ATTR_HP));
				int mana = Integer.parseInt(attributes.getValue(XmlConstants.TAG_HERO_ATTR_MANA));
				String name = attributes.getValue(XmlConstants.TAG_HERO_ATTR_MANA);
				
				mOutData.id = id;
				mOutData.name = name;
				mOutData.maxHp = hp;
				mOutData.maxMana = mana;
			}

		}
		
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);
			
			System.out.println("endElement, localName : " + localName + " uri : " + uri + " qName : " + qName);
		}
		
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			super.characters(ch, start, length);
		}
	}
	
	public void parseXml(FileHandle xmlFile, HeroData outData) {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		
		SAXParser saxParser = null;
		
		try {
			saxParser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {	
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		
		try {
			saxParser.parse(xmlFile.read(), new HeroDataHandler(outData));
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
